//
//  StatusPictureView.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/12/2.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//

import UIKit
import SDWebImage


private let pictureCellID = "pictureCellID"
private let pictureCellMargin: CGFloat = 5

class StatusPictureView: UICollectionView {
    
    //定义图片的url属性
    var imageURLs:[NSURL]?{
        
        //设置值
        didSet{
            
//            print(imageURLs?.count)
            
            if imageURLs?.count != nil {
                
//                testLabel.text = "\(imageURLs!.count)"
                
                self.backgroundColor = UIColor.whiteColor()
                
                let size = caclePictureViewSize()
                
                //snp_updateConstraints 已经约束了就更新约束, 没有约束就进行约束
                self.snp_updateConstraints { (make) -> Void in
                    make.size.equalTo(size)
                }
                
                //属性视图
                reloadData()
            }
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowlayout = UICollectionViewFlowLayout()
        
        flowlayout.minimumInteritemSpacing = pictureCellMargin
        
        flowlayout.minimumLineSpacing = pictureCellMargin
        
        super.init(frame: frame, collectionViewLayout: flowlayout)
        
        //设置数据源
        dataSource = self
        
        //注册cell
        registerClass(PictureCell.self, forCellWithReuseIdentifier:pictureCellID)
        
//        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        //        fatalError("init(coder:) has not been implemented")
        
        super.init(coder: aDecoder)
//        setupUI()
    }
    
//    private func setupUI(){
//        
//        addSubview(testLabel)
//        
//        //布局
//        testLabel.snp_makeConstraints { (make) -> Void in
//            
//            make.edges.equalTo(self.snp_edges)
//        }
//        
//    }
    
    
    
    /*
    单图会按照图片等比例显示
    多图的图片大小固定
    多图如果是4张，会按照 2 * 2 显示
    多图其他数量，按照 3 * 3 九宫格显示
    */
    private func caclePictureViewSize() -> CGSize{
        
        let imageCount = imageURLs?.count ?? 0
        
        let pictureViewW = width - StatusCellMargin * 2
        
        //精确小数点, 屏幕适配
        let itemW = (pictureViewW - pictureCellMargin * 2) / 3.001
        
        //设置collectionView itemSize
        //设置cell的大小
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemW, itemW)
        
        if imageCount == 0 {
            
            return CGSizeZero
        }
        
        //当对应的模型数据的图片数量为1 的 时候, 将从已经存入缓存中的 取出来, 然后重新设置图片的frame
        if imageCount == 1 {
            
            var itemSize = CGSizeMake(180, 120)
            
            //获取图片的url地址, 当做获取缓存的key
            let key = imageURLs?.first?.absoluteString ?? ""
            
             //从磁盘缓存中 根据对应 的图片的url的地址, 取出对应 图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            if image != nil {
            
                //让图片按图片 的原比例显示
                itemSize = image.size
            }
            
            //重新设置itemSize的尺寸
            itemSize.width = 180
            itemSize.height = image.size.width / image.size.height * width
            
            //进行布局
            layout.itemSize = itemSize
            
            return itemSize
        }
        
        if imageCount == 4 {
            
            let itemSize = CGSizeMake(itemW * 2 + pictureCellMargin, itemW * 2 + pictureCellMargin)
            
            return itemSize
        }
        
        let row = CGFloat((imageCount - 1) / 3 + 1)
        
        return CGSizeMake(pictureViewW , row * itemW + pictureCellMargin * row - 1)
    }
    
    
    //懒加载视图
    
//    //测试label
//    private lazy var testLabel:UILabel = UILabel(title:"" , color: UIColor.blackColor(), fontSize: 30.0, margin: 10)
    
}


//MARK:collection datasource
extension StatusPictureView:UICollectionViewDataSource{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
        
        cell.imageURL = imageURLs![indexPath.item]
        
        return cell
    }
}


//MARK: 自定义cell
class PictureCell:UICollectionViewCell{
    
    //定义外部设置属性
    var imageURL:NSURL?{
    
        didSet{
    
            picture.sd_setImageWithURL(imageURL)
        }
    }

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setupUI()
        
    }
    
    private func setupUI(){
    
        //一定要添加到contentView
        contentView.addSubview(picture)
        
        //布局
        picture.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //懒加载 子控件
    private lazy var picture:UIImageView = {
    
        let picture = UIImageView()
        
        picture.clipsToBounds = true
        
        //改变图片的显示模式
        picture.contentMode = .ScaleAspectFill
        
        return picture
    }()
}